﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;

/**
 * 创建时间：2014/11/3 15:06:37
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace CUWo.Common
{
    public class UserAgentHelper
    {
        public static string UserAgent { get; private set; }

        private const string htmlUserAgentToWebBrowser = @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN\"">
            <html>
                <head>
                    <script language=""JavaScript"" type=""text/JavaScript"">
                        function printUA()
                        {
                            return navigator.userAgent;
                        }
                    </script>
                </head>
                <body>
                </body>
            </html>";

        public static void GetUserAgentFromWebBrowser(Grid element)
        {
            if (element == null)
            {
                UserAgent = string.Empty;
                return;
            }

            if (!string.IsNullOrWhiteSpace(UserAgent))
            {
                return;
            }

            WebBrowser webView = new WebBrowser();
            webView.Visibility = Visibility.Collapsed;
            webView.IsScriptEnabled = true;
            webView.NavigateToString(htmlUserAgentToWebBrowser);
            ((ICollection<UIElement>)element.Children).Add(webView);
            webView.Navigated += delegate(object sender, System.Windows.Navigation.NavigationEventArgs args)
            {
                var ua = webView.InvokeScript("printUA");
                if (ua != null)
                {
                    UserAgent = ua.ToString();
                }
                ((ICollection<UIElement>)element.Children).Remove(webView);
            };
        }
    }
}
